import styles from "./AddPost.module.css";
import { nanoid } from '@reduxjs/toolkit'
import {
  type Post,
  useAddPostMutation,
//   useGetPostsQuery,
} from "../../app/services/posts";
import React, { useState } from "react";
export const AddPost = () => {
  const initialValue = { name: "" };
  const [post, setPost] = useState<Pick<Post, "name">>(initialValue);
  const [addPost, { isLoading }] = useAddPostMutation();

  // 绑定input 获取状态值
  const handleChange = ({ target }: React.ChangeEvent<HTMLInputElement>) => {
    setPost((prev) => ({
      ...prev,
      id:nanoid(),
      [target.name]: target.value, // 覆盖值
    }));
    console.log(post)
  };

  // 向server发送请求
  const handleAddPost = async () => {
    try {
      await addPost(post).unwrap();
      // 恢复初始值
      setPost(initialValue);
    } catch {
      console.log("err");
    }
  };

  return (
    <div className={styles.container}>
      {" "}
      <h2>添加一个新post</h2>
      <div>
        <input type="text" name="name" onChange={handleChange} />
      </div>
      <div>
        <button onClick={handleAddPost}>add post</button>
      </div>{" "}
    </div>
  );
};
